package com.cy.mall.service.comm.impl;

import java.util.Date;
import java.util.Map;

import javax.annotation.PostConstruct;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsRequest;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
import com.aliyuncs.profile.IClientProfile;
import com.cy.mall.comm.constant.Constants;
import com.cy.mall.comm.utils.JsonObjectMapper;
import com.cy.mall.comm.utils.SpringELUtils;
import com.cy.mall.dao.mongodb.SmsRecordDao;
import com.cy.mall.model.Result;
import com.cy.mall.model.doc.SmsRecord;
import com.cy.mall.model.enums.SmsType;
import com.cy.mall.service.BaseService;
import com.cy.mall.service.comm.SmsService;


/**
 * 阿里云短信服务
 *
 * @author tanyilin
 *
 * @create 2019年2月25日 下午3:08:25
 */
@Slf4j
@Service
public class AliyunSmsServiceImpl extends BaseService implements SmsService {

	@Value("${aliyun.sms.secret}")
    private String accessKeySecret;

    @Value("${aliyun.sms.key}")
    private String accessKeyId;

    /** 签名 */
    private final String sign = "马先生";
	
    /** 短信API产品名称（短信产品名固定，无需修改） */
    private final String product = "Dysmsapi";
    
    /** 短信API产品域名（接口地址固定，无需修改） */
    private final String domain = "dysmsapi.aliyuncs.com";
    
    private IAcsClient acsClient;
    
	@Autowired
	private SmsRecordDao smsRecordDao;
	
	@PostConstruct
    public void initBean() {
        //设置超时时间
        System.setProperty("sun.net.client.defaultConnectTimeout", "10000");
        System.setProperty("sun.net.client.defaultReadTimeout", "10000");
        try {
            DefaultProfile.addEndpoint("cn-shenzhen", "cn-shenzhen", product, domain);
        } catch (ClientException e) {
            log.error("initBean error:", e);
        }
        IClientProfile profile = DefaultProfile.getProfile("cn-shenzhen", accessKeyId,
                accessKeySecret);
        acsClient = new DefaultAcsClient(profile);
    }

	@Override
	public Result send(String mobile, SmsType type, Map<String, Object> params) {
		
		SendSmsRequest request = new SendSmsRequest();
		request.setMethod(MethodType.POST);
        request.setPhoneNumbers(mobile);
        request.setSignName(sign);
        request.setTemplateCode(type.getId());
        String json = JsonObjectMapper.toJson(params);
        request.setTemplateParam(json);
        log.info("发送短信 sms send to [{}], params [{}]", mobile, json);
        
        //记录短信 到 mongoDB
        String context = SpringELUtils.getValue(type.getContext(), params);
        SmsRecord smsRecord = new SmsRecord();
        smsRecord.setMobile(mobile);
        smsRecord.setContext(context);
        smsRecord.setType(type);
        smsRecord.setCreateTime(new Date());
        
        if (!Constants.IS_PROD) {
            log.info("非prod环境不发送真实短信");
            //smsRecord.setStatus("SUCCESS");
            //smsRecordDao.insert(smsRecord);
            return Result.success();
        }
        
        SendSmsResponse sendSmsResponse = null;
        try {
            sendSmsResponse = acsClient.getAcsResponse(request);
        } catch (ClientException e) {
            log.error("acsClient.getAcsResponse(request) error:", e);
            smsRecord.setStatus("EXCEPTION");
            smsRecordDao.insert(smsRecord);
            return Result.fail("系统异常");
        }
        
        Result result = new Result();
        
        if(sendSmsResponse.getCode() != null && "OK".equals(sendSmsResponse.getCode())) {
            result.setOk(true);
            result.setMessage("发生成功");
            smsRecord.setStatus("SUCCESS");
        } else {
        	result.setMessage("发生失败");
            smsRecord.setStatus("FAIL");
        }
        smsRecordDao.insert(smsRecord);
        
        //短信发送成功
        return result;
	}

	
}
